package com.phkj.qdh.ui.fragment.mynotice

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.QuickAdapterHelper
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.bean.FileUploadBean
import com.phkj.qdh.databinding.FragmentNoticeRectifyBinding
import com.phkj.qdh.net.FILE_UPLOAD
import com.phkj.qdh.net.msg
import com.phkj.qdh.ui.adapter.ImagerViewAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAddAdapter
import com.phkj.qdh.ui.dialog.CommonConfirmDialog
import com.phkj.qdh.ui.dialog.CommonConfirmListener
import com.phkj.qdh.ui.fragment.user.UserVM
import com.phkj.qdh.ui.fragment.user.getUserVMProvider
import com.phkj.qdh.utils.FileHelper
import com.phkj.qdh.utils.GetImgContract
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.TakePhoto
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.requestMain
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import rxhttp3.RxHttp
import rxhttp3.toFlowResponse
import java.io.File
import java.text.SimpleDateFormat
import java.util.GregorianCalendar
import java.util.HashMap
import java.util.Locale

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 *
 */
class NoticeRectifyFragment : Fragment() {
    private var param1: Int? = null
    private var param2: Int? = null
    private var pliceId: Int? = null
    private var _binding: FragmentNoticeRectifyBinding? = null
    private lateinit var vm: UserVM

    private val binding get() = _binding!!
    private val iVAdapter by lazy { ImagerViewAdapter() }
    private val iVAddAdapter by lazy { ImagerViewAddAdapter() }
    private var imageUri: Uri? = null
    private var filePath: String = ""
    private val selectImg = registerForActivityResult(GetImgContract()) { uri ->
        uri?.let {
            LogUtil.E(it.toString())
            val file = FileHelper.getFileAbsolutePath(requireContext(), it)
            uploadImg(file)
        }
    }
    private val takePic =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { boolean ->
            if (boolean) {
                try {
                    imageUri?.let { uri ->
                        val option = BitmapFactory.Options()
                        option.inPreferredConfig = Bitmap.Config.RGB_565
                        val bitmap = BitmapFactory.decodeStream(
                            requireContext().contentResolver.openInputStream(uri)
                            ,null,option
                        )
                        val yasuohou = TakePhoto.scaleBitmap(bitmap,0.5f)
                        val path = TakePhoto.saveBitmap2File(yasuohou)
                        uploadImg(path)
                    }

                } catch (e: Exception) {

                }

            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getInt(ARG_PARAM1)
            param2 = it.getInt(ARG_PARAM2)
            pliceId = it.getInt("plice_id")
        }
        requireActivity().onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentNoticeRectifyBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getUserVMProvider())[UserVM::class.java]
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            rvLawSubmit.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(requireContext(), R.color.transparent),
                        28,
                        RecyclerView.HORIZONTAL
                    )
                )
            }

            btnOk.setOnClickListener {
                val dialog = CommonConfirmDialog.getInstance("提交", "确定要提交反馈吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        feedBack()
                    }

                    override fun dCancel() {
                    }

                })
                dialog.show(parentFragmentManager, "")

            }
        }

        val helper = QuickAdapterHelper.Builder(iVAdapter).build()
        helper.addBeforeAdapter(iVAddAdapter)
        iVAddAdapter.add("s")
        binding.rvLawSubmit.adapter = helper.adapter

        iVAdapter.addOnItemChildClickListener(R.id.iv_delete){adapter,_,pos->
            val dialog = CommonConfirmDialog.getInstance(
                "删除图片", "确定要删除图片吗", "确定", "取消"
            )
            dialog.setCancelListener(object : CommonConfirmListener {
                override fun dOk() {
                    adapter.removeAt(pos)
                }

                override fun dCancel() {
                    takePhoto()
                }

            })
            dialog.show(parentFragmentManager, "")
        }

        iVAddAdapter.setOnItemClickListener { adapter, data, pos ->
            if (iVAdapter.items.size >= 6) {
                ToastUtils.show("图片数量不能超过6张")
                return@setOnItemClickListener
            }
            XXPermissions.with(requireContext())
                .permission(arrayListOf(Permission.READ_MEDIA_IMAGES, Permission.CAMERA))
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (allGranted) {
                            val dialog = CommonConfirmDialog.getInstance(
                                "上传图片", "请选择上传方式", "选择照片", "拍照"
                            )
                            dialog.setCancelListener(object : CommonConfirmListener {
                                override fun dOk() {
                                    selectImg.launch(null)
                                }

                                override fun dCancel() {
                                    takePhoto()
                                }

                            })
                            dialog.show(parentFragmentManager, "")
                        }
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        super.onDenied(permissions, doNotAskAgain)
                    }
                })
        }

        launchAndRepeatWithViewLifecycle {
            vm.lawFeedback.collectLatest {
                if (it) {
                    ToastUtils.show("反馈成功")
                    parentFragmentManager.popBackStack()
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.teamFeedback.collectLatest {
                if (it) {
                    ToastUtils.show("反馈成功")
                    parentFragmentManager.popBackStack()
                }
            }
        }
    }

    private fun feedBack() {
        val map = HashMap<String, Any?>()
        map["problemId"] = param1
        map["feedback"] = binding.edtQuest.text.toString()
        map["images"] = iVAdapter.items
        map["responsiblePerson"] = pliceId
        if (param2 == 1) {
            vm.teamFeedback(map)
        } else {
            vm.lawFeedback(map)
        }
    }

    private fun takePhoto() {
        val simpleDate = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
        val fileName = simpleDate.format(GregorianCalendar().time) + ".jpg"
        var outputImage = File(requireContext().externalCacheDir, fileName)
        if (outputImage.exists()) {
            outputImage.delete()
        }
        outputImage.createNewFile()
        imageUri = if (Build.VERSION.SDK_INT >= 24) {
            FileProvider.getUriForFile(
                requireContext(), "com.phkj.qdh.fileprovider", outputImage
            )
        } else {
            Uri.fromFile(outputImage)
        }
        filePath = outputImage.absolutePath
        takePic.launch(imageUri)

    }

    private fun uploadImg(path: String) {
        requestMain {
            RxHttp.postForm(FILE_UPLOAD).addFile("file", path).toFlowResponse<FileUploadBean>()
                .catch { cause ->
                    ToastUtils.show(cause.msg)
                }.collectLatest {
                    delay(500)
                    iVAdapter.add(it.url)
                }
        }
    }


    companion object {
        /**
         */
        @JvmStatic
        fun newInstance(param1: Int, pliceId: Int, type: Int) = NoticeRectifyFragment().apply {
            arguments = Bundle().apply {
                putInt(ARG_PARAM1, param1)
                putInt("plice_id", pliceId)
                putInt(ARG_PARAM2, type)
            }
        }
    }
}